//
//  WKDownLoadManger.m
//  WeKeTang
//
//  Created by ichina on 2017/9/21.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKDownLoadManger.h"

@interface WKDownLoadManger()

@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;

@property (nonatomic, assign) BOOL isSupend;

@property (nonatomic, strong) AFURLSessionManager *manger;

@end

@implementation WKDownLoadManger

+ (instancetype)defaultInstance {
    static WKDownLoadManger *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
- (instancetype)init{
    if (self = [super init]) {
        
        self.tasks = [NSMutableDictionary dictionary];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.manger = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        
    }
    
    return self;
}
#pragma mark - 下载
- (void)downloadFileWithUrl:(NSString *_Nullable)url
            progressHandler:(progressBlock _Nullable )progressBlock
            completeHandler:(completeBlock _Nullable )completeBlock
              errorHandlerk:(errorBlock _Nullable )errorBlock{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    //
//    __weak typeof(self) weakSelf = self;
  self.downloadTask =[self.manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
    
        if (progressBlock) {
            
            progressBlock(downloadProgress);
        }
         
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:path];
        return [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
        
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (error) {
            if (errorBlock) {
                errorBlock(error);
            }
        }else{
            if (completeBlock) {
                completeBlock(response, [filePath absoluteString]);
            }
        }
    }];
    
    
    [self.downloadTask resume];
}
- (void)suspendDownLoad{
    
    [self.downloadTask cancel];
    self.downloadTask = nil;
}


#pragma mark - 暂停下载
- (void)suspendDownLoadWithUrl:(NSString*)url{
    
//    NSURLSessionDownloadTask *task = self.tasks[url];
    NSLog(@"---------------%@",self.downloadTask);
    _isSupend = YES;
     [self.downloadTask cancel];
//    if (task) {
//        [task suspend];
//    }
}

@end
